<?php 
class cmshopApi_base extends Helper_interface_base
{
	public $AuthToken; //用户 token
	public $verb; // 应用 API 名,写在 API 接口中
	public $xmlns='xmlns="cmshop:apis:shopapi"'; //
	function __construct(){
		$this->_loadconfig();
	}
	function _loadconfig(){

	}
	
	function dateTime($timestamp=null){
	    if(strlen($timestamp)){
		    return gmdate('Y-m-d\TH:i:s.Z\Z',$timestamp);
		}else{
            return gmdate('Y-m-d\TH:i:s.Z\Z');
        }
	}
	
	function _lengcode($str,$len,$type='md5'){
        if($type=='md5'){
            $str2=md5($str);
        }elseif($type=='be'){
            $str2=$str.md5($str);
        }elseif($type=='ed'){
            $str2=md5($str).$str;
        }elseif($type=='time'){
            $str2=md5($str.'.'.time());
        }elseif($type=='dmd5'){
            $str2=md5(md5($str));
        }elseif($type=='2md5'){
            $str2=md5($str.':'.$str);
        }
        
        $start=strlen($str2)-$len;
        if($start<0) $start=0;
        $start=rand(0,$start);
        $str3=substr($str2,$start,$len);
        return $str3;
    }
    /***
     * 验证  request 过来的 数据是否正确 
     *  解析 request 过来的 数据 
     */
    function xmlrequest(){
        @$app=$_SERVER['HTTP_CMSTORE_API_APP_NAME'];
        @$cert=$_SERVER['HTTP_CMSTORE_API_CERT_NAME'];
        @$this->call=$_SERVER['HTTP_CMSTORE_API_CALL_NAME'];
        $input=file_get_contents('php://input');
        Helper_tlog::tofile('shopapi.txt',array('app'=>$app,'cert'=>$cert,'call'=>$this->call));
        Helper_tlog::tofile('shopapi.txt',$input);
        // 关键 字段 不能为空.
        if(!(strlen($app)&&strlen($cert)&&strlen($this->call)&&strlen($input))){
            throw new Exception_ApiClientInvalidate('');
        }
        /// 解析  xml 不能出错 .
        // 验证 xml , 首字段的  名称,属性 
        $responseDoc = new DomDocument();
		if(!@$responseDoc->loadXML($input)){
            throw new Exception_ApiClientInvalidate('');
        }
		$xml=$responseDoc->getElementsByTagName($this->call.'Request');
		if($xml->item(0)->getAttribute('xmlns')!='cmshop:apis:shopapi'){
            throw new Exception_ApiClientInvalidate('');
        }
        $this->input=Helper_xml::xmlparse($xml);
        $this->input=$this->input[$this->call.'Request'];
        // 解析 是否成功 .
        if(empty($this->input)) throw new Exception_RequestFormatInvalidate('');
        //应用是合法的  , 在数据库中 可 找到.  
        $appclient=Appclient::find('app_name=? And app_cert=? And status&1',$app,$cert)->getOne();
        if($appclient->isNewRecord()){ throw new Exception_ApiClientInvalidate('');}
        $this->appclient=$appclient->toArray();
        return $this->appclient['app_id'];
    }
    /****
     * AuthToken
     */         
    function checkAuthToken(){
        if(!isset($this->input['RequesterCredentials']['AuthToken'])){
            throw new Exception_AuthTokenInvalidate('');
        }
        $token=$this->input['RequesterCredentials']['AuthToken'];
        $t=Token::find('token=? And hardexpirationtime<?',$token,$this->extime('token'))->getOne();
        if($t->isNewRecord()){
            $this->token=false;
            throw new Exception_AuthTokenInvalidate('');
        }else{
            $this->store=$t->store;
            $this->token=$t->toArray();
        }
        return $this->token;
    }
    /**
     * 输出 response 
     */         
    function xmlresponse($xmlArr){
        if ($xmlArr instanceof SimpleXMLElement ){
	        $xmlArr['requestXML']=$xmlArr;
	    }elseif(is_string($xmlArr)){
    	    $responseBody=$xmlArr;
	    }
	    if(empty($responseBody)){
    	    $xmlArr=array(
    	        $this->verb.'Response '.$this->xmlns=>$xmlArr,
    	    );
            $responseBody=Helper_xml::simpleArr2xml($xmlArr);
		}
        return $responseBody;
    }
    
    function extime($type='sessionid'){
        switch($type){
            case 'token': $ex=15552000; break;
            case 'sessionid':$ex=1800; break;
            default :$ex=0;
        }
        return CURRENT_TIMESTAMP+ $ex;
    }
    
    function stringInput($fieldName,$arr=null){
        if(is_array($arr)){
            if(isset($arr[$fieldName])){
               return $arr[$fieldName];
            }
        }else{
            if(isset($this->input[$fieldName])){
                return $this->input[$fieldName];
            }
        }
        return '';
    }
}
class Exception_RequestFormatInvalidate extends QException {}
class Exception_AuthTokenInvalidate extends QException {} 
class Exception_ApiClientInvalidate extends QException {}